package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.dto.DishDto;
import com.example.domain.entity.Dish;
import com.example.domain.entity.DishFlavor;
import com.example.mapper.DishMapper;
import com.example.service.ICategoryService;
import com.example.service.IDishFlavorService;
import com.example.service.IDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author xiaoduan
 * @since 2024-07-30
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IDishFlavorService dishFlavorService;

    @Override
    public void saveDishAndDishFlavor(DishDto dishDto) {
        save(dishDto);
        for (DishFlavor flavor : dishDto.getFlavors()) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    @Override
    public DishDto getDishAndDishFlavorById(Long id) {
        Dish byId = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(byId,dishDto);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,byId.getId() );
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public void updateDishAndDishFlavorByDishDto(DishDto dishDto) {
        updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(String.valueOf(dishDto.getId())),DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);
        dishFlavorService.saveOrUpdateBatch(dishDto.getFlavors().stream().map((flavor) -> {
                flavor.setDishId(dishDto.getId());
            return flavor;
        }).collect(Collectors.toList()));
    }
}
